<template>
  <el-autocomplete
    ref="autocomplete"
    v-model="compeleteState"
    :fetch-suggestions="querySearch"
    :clearable="clearable"
    :placeholder="placeholder"
    @select="handleSelect"
    @blur="handleBlur"
    @focus="handleFocus"
    @input="handleInput"
    @clear="handleClear"
    @keyup.enter.native="handleKeyup"
  >
    <!-- <template #suffix>
      <el-icon class="el-input__icon" @click="handleIconClick">
        <edit />
      </el-icon>
    </template> -->
    <template #default="{ item }" v-if="customSlot">
      <div class="item">
        <div class="content">
          <div class="value">{{ item.value }}</div>
          <span class="desc">{{ item.count }}</span>
        </div>
        <el-icon class="icon-delete" @click.stop="del(item)"
          ><Delete
        /></el-icon>
      </div>
    </template>
  </el-autocomplete>
</template>

<script lang="ts" setup>
const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  },
  clearable: {
    type: Boolean,
    default: false,
  },
  querySearchStr: {
    type: String,
    required: true,
  },
  placeholder: {
    type: String,
    default: "请输入",
  },
  customSlot: {
    type: Boolean,
    default: false
  }
});

const { modelValue, clearable, querySearchStr, placeholder, customSlot } = toRefs(props);

const emit = defineEmits();
const autocomplete = ref();
const compeleteState = computed({
  get() {
    return modelValue.value;
  },
  set(value) {
    emit("update:modelValue", value);
  },
});
const timerId = ref(null);
const countFlag = ref(false);
const currentRquest = ref([]);
const currentList = ref([]);
const restaurants = ref([]);
const querySearch = (queryString: string, cb: any) => {
  // clearTimeout(timerId.value);
  //   const results = queryString && queryString.length >= 1
  //     ? restaurants.value.filter(createFilter(queryString))
  //     : restaurants.value;
  let results = [];
  if (!queryString) {
    storeInit();
    results = restaurants.value;
  }
  if (queryString && queryString.length >= 1) {
    storeInit();
    results = restaurants.value.filter(createFilter(queryString));
    if (!results.length) {
      results = restaurants.value;
    }
  }
  if (queryString && queryString.length >= 2) {
    restaurants.value = currentRquest.value;
    results = restaurants.value.filter(createFilter(queryString));
    if (!results.length) {
      results = restaurants.value;
    }
  }
  // if (queryString && results.length == 1) {
  //   timerId.value = setTimeout(() => {
  //     // 模拟延时
  //     compeleteState.value = results[0].value;
  //   }, 3000);
  // }
  cb(results);
};
const createFilter = (queryString: string) => {
  return (restaurant) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    );
  };
};
const loadAll = () => {
  return [
    { value: "vue", count: "1", link: "https://github.com/vuejs/vue" },
    {
      value: "element",
      count: "1",
      link: "https://github.com/ElemeFE/element",
    },
    {
      value: "cooking",
      count: "1",
      link: "https://github.com/ElemeFE/cooking",
    },
    {
      value: "mint-ui",
      count: "1",
      link: "https://github.com/ElemeFE/mint-ui",
    },
    { value: "vuex", count: "1", link: "https://github.com/vuejs/vuex" },
    {
      value: "vue-router",
      count: "1",
      link: "https://github.com/vuejs/vue-router",
    },
    { value: "babel", count: "1", link: "https://github.com/babel/babel" },
  ];
};

const minNumValue = computed(() => {
  return currentList.value.reduce((min, item) => {
    return item.count < min.count ? item : min;
  }, currentList.value[0]);
});

const handleSelect = (item) => {
  // 当选择某个选项时，可以在这里添加逻辑
  // countFn(item.value);
  // countFlag.value = true;
};

const handleInput = (value) => {
  // 当输入框内容变化时，可以在这里添加逻辑
  countFlag.value = false;
};

// 清空内容输入框失去焦点
const handleClear = () => {
  document.activeElement.blur();
};

const handleBlur = () => {
  // 如果需要在失去焦点时执行某些操作，可以在这里添加逻辑
  // if (!countFlag.value) {
  //   countFn(compeleteState.value);
  // }
};

// 执行存储
const executeStorage = () => {
  if (compeleteState.value) {
    countFn(compeleteState.value);
  }
};

const countFn = (value) => {
  if (currentList.value.some((item) => item.value === value)) {
    currentList.value.forEach((item) => {
      if (item.value === value) {
        item.count++;
      }
    });
    localStorage.setItem(
      `store${querySearchStr.value}`,
      JSON.stringify(currentList.value)
    );
  } else if (value && currentList.value.length >= 4) {
    currentList.value = currentList.value.filter(
      (item) => item.value !== minNumValue.value.value
    );
    currentList.value.unshift({ value: value, count: 1 });
    localStorage.setItem(
      `store${querySearchStr.value}`,
      JSON.stringify(currentList.value)
    );
  } else if (value) {
    // 如果输入的值不在列表中且列表长度小于10，则添加新项
    currentList.value.unshift({ value: value, count: 1 });
    localStorage.setItem(
      `store${querySearchStr.value}`,
      JSON.stringify(currentList.value)
    );
  }

  currentList.value =
    JSON.parse(localStorage.getItem(`store${querySearchStr.value}`)) || [];
  restaurants.value = currentList.value;
};

const handleFocus = () => {
  autocomplete.value.suggestions = []
  storeInit();
  currentRquest.value = loadAll();
};

const handleKeyup = (event) => {
  // event.target.blur();
  // countFlag.value = true;
  executeStorage()
  emit("keyup");
};

const storeInit = () => {
  currentList.value = localStorage.getItem(`store${querySearchStr.value}`)
    ? JSON.parse(localStorage.getItem(`store${querySearchStr.value}`))
    : [];
  restaurants.value = currentList.value;
};

const del = (item) => {
  // console.log("autocomplete", autocomplete.value);
  let list =
    (localStorage.getItem(`store${querySearchStr.value}`) &&
      JSON.parse(localStorage.getItem(`store${querySearchStr.value}`))) ||
    [];
  console.log('list', list)
  const arr = list.filter(
    (it) => it.value !== item.value
  );
  localStorage.setItem(`store${querySearchStr.value}`, JSON.stringify(arr));
  autocomplete.value.suggestions = arr; // 过滤后的数组重新赋值
  storeInit() // 删除后重新获取缓存的数组更新数据
  // autocomplete.value.handleQueryChange(compeleteState.value); // 手动触发查询变化

};

onMounted(() => {
  autocomplete.value.suggestions = []
  storeInit();
});

defineExpose({
  executeStorage,
});
</script>

<style lang="scss" scoped>
.content {
  margin-right: 6px;
}
.value,
.desc {
  height: 20px;
  line-height: 20px;
}
.item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.icon-delete:hover {
  color: #f56c6c;
  cursor: pointer;
}
</style>
